<template>
    <view class="social-comment-container">
        <!-- 评论头部统计 -->
        <view class="comment-header">
            <text class="comment-count">{{ commentData?.total || 0 }}条评论</text>
        </view>

        <!-- 评论输入框 -->
        <view class="comment-input-section">
            <view class="input-box" @click="showCommentModal">
                <text class="placeholder">说点什么...</text>
            </view>
        </view>

        <!-- 评论列表 -->
        <view class="comment-list" v-if="displayComments.length > 0">
            <view class="comment-item" v-for="(item, index) in displayComments" :key="item.id">
                <!-- 用户头像 -->
                <view class="user-avatar">
                    <up-avatar :src="item.avatar || defaultAvatar" size="36" shape="circle"></up-avatar>
                </view>

                <!-- 评论内容区 -->
                <view class="comment-content">
                    <!-- 用户信息 -->
                    <view class="user-info">
                        <text class="username">{{ item.nickName || "匿名用户" }}</text>
                        <text class="time">{{ formatTime(item.createTime) }}</text>
                    </view>

                    <!-- 评论文本 -->
                    <view class="comment-text">
                        <text>{{ getDisplayContent(item) }}</text>
                        <text v-if="item.content && item.content.length > 30" class="expand-toggle"
                            @click="toggleComment(index)">
                            {{ item.expanded ? "收起" : "展开" }}
                        </text>
                    </view>

                    <!-- 评论操作 -->
                    <view class="comment-actions">
                        <view class="action-item" @click="handleLike(item.id)">
                            <up-icon :name="item.isLiked ? 'thumb-up-fill' : 'thumb-up'"
                                :color="item.isLiked ? '#ff0202' : '#999'" size="16"></up-icon>
                            <text class="action-text" :class="{ liked: item.isLiked }">
                                {{ item.likeCount > 0 ? item.likeCount : "赞" }}
                            </text>
                        </view>
                        <view class="action-item" @click="replyTo(item)">
                            <up-icon name="chat" color="#999" size="16"></up-icon>
                            <text class="action-text">回复</text>
                        </view>
                        <view class="action-item" v-if="item.isOwner" @click="handleDelete(item.id)">
                            <up-icon name="trash" color="#999" size="16"></up-icon>
                            <text class="action-text">删除</text>
                        </view>
                    </view>

                    <!-- 回复列表 -->
                    <view class="reply-list" v-if="item.replies && item.replies.length > 0">
                        <view class="reply-item" v-for="(reply, replyIndex) in getVisibleReplies(item)" :key="reply.id">
                            <!-- 回复者头像 -->
                            <view class="reply-avatar">
                                <up-avatar :src="reply.avatar || defaultAvatar" size="32" shape="circle"></up-avatar>
                            </view>

                            <!-- 回复内容 -->
                            <view class="reply-content">
                                <view class="reply-user-info">
                                    <text class="reply-username">{{
                                        reply.nickName || "匿名用户"
                                        }}</text>
                                    <text class="reply-time">{{
                                        formatTime(reply.createTime)
                                        }}</text>
                                </view>
                                <view class="reply-text">
                                    <text>{{ getDisplayReplyContent(reply) }}</text>
                                    <text v-if="reply.content && reply.content.length > 30" class="expand-toggle"
                                        @click="toggleReply(item.id, replyIndex)">
                                        {{ reply.expanded ? "收起" : "展开" }}
                                    </text>
                                </view>
                                <view class="reply-actions">
                                    <view class="action-item" @click="handleLike(reply.id)">
                                        <up-icon :name="reply.isLiked ? 'thumb-up-fill' : 'thumb-up'"
                                            :color="reply.isLiked ? '#ff0202' : '#999'" size="14"></up-icon>
                                        <text class="action-text" :class="{ liked: reply.isLiked }">
                                            {{ reply.likeCount > 0 ? reply.likeCount : "赞" }}
                                        </text>
                                    </view>
                                    <view class="action-item" @click="replyTo(item, reply)">
                                        <text class="action-text">回复</text>
                                    </view>
                                    <view class="action-item" v-if="item.isOwner" @click="handleDelete(reply.id)">
                                        <text class="action-text">删除</text>
                                    </view>
                                </view>
                            </view>
                        </view>

                        <!-- 查看更多回复 -->
                        <view class="view-more-replies" v-if="hasMoreReplies(item)" @click="viewMoreReplies(item.id)">
                            <text class="view-more-text">展开更多{{
                                item.replies.length - getVisibleReplies(item).length
                                }}条回复</text>
                            <up-icon name="arrow-down" color="#999" size="14"></up-icon>
                        </view>

                        <!-- 收起回复 -->
                        <view class="view-more-replies" v-if="shouldShowCollapse(item)"
                            @click="collapseReplies(item.id)">
                            <text class="view-more-text">收起</text>
                            <up-icon name="arrow-up" color="#999" size="14"></up-icon>
                        </view>
                    </view>
                </view>
            </view>
        </view>

        <!-- 空评论状态 -->
        <view class="empty-comments" v-else>
            <up-icon name="chat" size="48" color="#ccc"></up-icon>
            <text class="empty-text">暂无评论，快来抢沙发</text>
        </view>

        <!-- 查看全部评论按钮 -->
        <view class="view-all-comments" v-if="
            props.displayCount > 0 &&
            props.displayCount < (commentData?.list?.length || 0)
        " @click="viewAllComments">
            <text class="view-all-text">查看全部{{
                commentData?.total || commentData?.list?.length
                }}条评论</text>
            <up-icon name="arrow-right" color="#999" size="14"></up-icon>
        </view>

        <!-- 评论弹窗 -->
        <up-popup mode="bottom" :show="showModal" round="20" closeable @close="closeCommentModal" :custom-style="{
            zIndex: 99999,
            marginBottom: keyboardHeight + 'px',
            transition: 'margin-bottom 0.3s cubic-bezier(0.4, 0, 0.2, 1)',
        }">
            <view class="comment-modal">
                <!-- 弹窗头部 -->
                <view class="modal-header">
                    <text class="modal-title">{{
                        isReply ? "回复评论" : "发表评论"
                        }}</text>
                </view>
                <!-- 回复提示 -->
                <view class="reply-info" v-if="isReply">
                    <text class="reply-text">回复 {{ replyToUser }}</text>
                    <up-icon name="close" size="16" color="#999" @click="cancelReply"></up-icon>
                </view>

                <!-- 输入区域 -->
                <view class="modal-content">
                    <textarea class="comment-textarea" v-model="commentContent" :adjust-position="false"
                        :placeholder="isReply ? '回复内容...' : '请输入评论内容...'" :show-confirm-bar="false" :auto-height="true"
                        :focus="modalFocused" :cursor-spacing="20" maxlength="500" @focus="onTextareaFocus"
                        @blur="onTextareaBlur"></textarea>

                    <view class="modal-footer">
                        <text class="char-count" :class="{ 'char-warning': commentContent.length > 450 }">
                            {{ commentContent.length }}/500
                        </text>
                        <view>
                            <up-button type="primary" size="mini" shape="circle" :text="isReply ? '回复' : '发表'"
                                :disabled="commentContent.length === 0" @click="submitComment" :customStyle="{
                                    width: '100rpx',
                                    height: '50rpx',
                                    fontSize: '24rpx',
                                    background: commentContent.length > 0 ? '#ff0202' : '#ccc',
                                    border: 'none',
                                }"></up-button>
                        </view>
                    </view>
                </view>
            </view>
        </up-popup>
    </view>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, computed } from "vue";

// 定义 props
const props = defineProps({
    // 评论数据
    data: {
        type: Object,
        default: () => ({
            total: 0,
            list: [],
        }),
    },
    // 当前用户ID
    userId: {
        type: [String, Number],
        default: "",
    },
    // 要显示的评论数量，默认显示所有评论
    displayCount: {
        type: Number,
        default: 0,
    },
});

// 定义 emits
const emit = defineEmits([
    "like",
    "delete",
    "submit",
    "load-more-replies",
    "view-all",
    "validate-user",
]);

// 响应式数据
const commentData = ref(props.data);
const showModal = ref(false);
const modalFocused = ref(false);
const commentContent = ref("");
const isReply = ref(false);
const replyToUser = ref("");
const replyToId = ref(null);
const replyToReplyId = ref(null);
const keyboardHeight = ref(0); // 键盘高度
const isKeyboardShown = ref(false); // 键盘是否显示

// 计算属性：要显示的评论列表
const displayComments = computed(() => {
    if (props.displayCount > 0 && commentData.value.list) {
        console.log("Displaying", props.displayCount, "comments");
        return commentData.value.list.slice(0, props.displayCount);
    }
    return commentData.value.list || [];
});

// 每个评论默认显示的回复数
const DEFAULT_REPLY_COUNT = 2;
// 展开的回复ID记录
const expandedReplies = reactive({});

// 默认头像
const defaultAvatar =
    "";

// 监听键盘高度变化
const handleKeyboardHeightChange = (res) => {
    // 使用防抖和动画来减少跳动
    setTimeout(() => {
        keyboardHeight.value = res.height;
    }, 10);
};

// 格式化时间
const formatTime = (time) => {
    if (!time) return "刚刚";

    // 如果是时间戳，转换为日期对象
    const date = new Date(time);
    const now = new Date();
    const diff = now - date;

    // 小于1分钟显示刚刚
    if (diff < 60 * 1000) {
        return "刚刚";
    }

    // 小于1小时显示分钟数
    if (diff < 60 * 60 * 1000) {
        return `${Math.floor(diff / (60 * 1000))}分钟前`;
    }

    // 小于24小时显示小时数
    if (diff < 24 * 60 * 60 * 1000) {
        return `${Math.floor(diff / (60 * 60 * 1000))}小时前`;
    }

    // 其他情况显示日期
    return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, "0")}-${date.getDate().toString().padStart(2, "0")}`;
};

// 获取评论显示内容
const getDisplayContent = (comment) => {
    if (!comment.content) return "";

    // 如果评论已展开或内容长度小于等于100，显示完整内容
    if (comment.expanded || comment.content.length <= 30) {
        return comment.content;
    }

    // 否则只显示前100个字符并添加省略号
    return comment.content.substring(0, 30) + "...";
};

// 获取回复显示内容
const getDisplayReplyContent = (reply) => {
    if (!reply.content) return "";

    // 如果回复已展开或内容长度小于等于100，显示完整内容
    if (reply.expanded || reply.content.length <= 30) {
        return reply.content;
    }

    // 否则只显示前100个字符并添加省略号
    return reply.content.substring(0, 30) + "...";
};

// 切换评论展开状态
const toggleComment = (index) => {
    console.log("切换评论展开状态:", index);
    // 使用 Vue 3 的响应式更新方式
    const comment = commentData.value.list[index];

    // 切换展开状态
    const newExpanded = !comment.expanded;
    console.log("当前展开状态:", comment.expanded, "新状态:", newExpanded);

    // 更新单个评论的展开状态
    commentData.value.list[index] = {
        ...comment,
        expanded: newExpanded,
    };

    // 触发响应式更新
    commentData.value = { ...commentData.value };
    console.log("更新后的评论:", commentData.value.list[index]);
};

// 切换回复展开状态
const toggleReply = (commentId, replyIndex) => {
    console.log("切换回复展开状态:", commentId, replyIndex);
    // 找到对应的评论
    const commentIndex = commentData.value.list.findIndex(
        (c) => c.id === commentId
    );
    if (commentIndex === -1) return;

    // 获取评论和回复
    const comment = commentData.value.list[commentIndex];
    if (!comment.replies || comment.replies.length <= replyIndex) return;

    // 切换展开状态
    const reply = comment.replies[replyIndex];
    const newExpanded = !reply.expanded;
    console.log("当前回复展开状态:", reply.expanded, "新状态:", newExpanded);

    // 更新单个回复的展开状态
    const newReplies = [...comment.replies];
    newReplies[replyIndex] = {
        ...reply,
        expanded: newExpanded,
    };

    // 更新评论数据
    commentData.value.list[commentIndex] = {
        ...comment,
        replies: newReplies,
    };

    // 触发响应式更新
    commentData.value = { ...commentData.value };
    console.log(
        "更新后的回复:",
        commentData.value.list[commentIndex].replies[replyIndex]
    );
};

// 获取可见的回复
const getVisibleReplies = (comment) => {
    if (!comment.replies || comment.replies.length === 0) return [];

    // 如果该评论的回复已展开，显示所有回复
    if (expandedReplies[comment.id]) {
        return comment.replies;
    }

    // 否则只显示前 DEFAULT_REPLY_COUNT 条回复
    return comment.replies.slice(0, DEFAULT_REPLY_COUNT);
};

// 判断是否还有更多回复
const hasMoreReplies = (comment) => {
    if (!comment.replies || comment.replies.length === 0) return false;
    return (
        !expandedReplies[comment.id] && comment.replies.length > DEFAULT_REPLY_COUNT
    );
};

// 判断是否应该显示收起按钮
const shouldShowCollapse = (comment) => {
    if (!comment.replies || comment.replies.length === 0) return false;
    return (
        expandedReplies[comment.id] && comment.replies.length > DEFAULT_REPLY_COUNT
    );
};

// 显示评论弹窗
const showCommentModal = () => {
    emit("validate-user");
    isReply.value = false;
    replyToUser.value = "";
    replyToId.value = null;
    replyToReplyId.value = null;
    commentContent.value = "";
    showModal.value = true;
    console.log("显示评论弹窗:", showModal.value);

    // 延迟设置焦点以确保弹窗完全显示
    setTimeout(() => {
        modalFocused.value = true;
    }, 100);
};

// 关闭评论弹窗
const closeCommentModal = () => {
    modalFocused.value = false;
    showModal.value = false;
    console.log("关闭评论弹窗:", showModal.value);
};

// 取消回复
const cancelReply = () => {
    isReply.value = false;
    replyToUser.value = "";
    replyToId.value = null;
    replyToReplyId.value = null;
};

// 回复评论
const replyTo = (comment, reply = null) => {
    emit("validate-user");
    console.log("回复评论:", comment, reply);
    isReply.value = true;
    if (reply) {
        // 回复子评论
        replyToUser.value = reply.nickName;
        replyToId.value = comment.id;
        replyToReplyId.value = reply.id;
    } else {
        // 回复主评论
        replyToUser.value = comment.nickName;
        replyToId.value = comment.id;
        replyToReplyId.value = null;
    }
    commentContent.value = "";
    showModal.value = true;
    console.log("显示回复弹窗:", showModal.value);

    // 延迟设置焦点以确保弹窗完全显示并触发键盘
    setTimeout(() => {
        modalFocused.value = true;
        // 额外延时确保键盘弹出
        setTimeout(() => {
            modalFocused.value = true;
        }, 10);
    }, 10);
};

// 处理点赞
const handleLike = (id) => {
    emit("like", { id, type: "comment" });
};

// 处理删除
const handleDelete = (id) => {
    uni.showModal({
        title: "提示",
        content: "确定要删除这条评论吗？",
        success: (res) => {
            if (res.confirm) {
                emit("delete", { id, type: "comment" });
            }
        },
    });
};

// 查看更多回复
const viewMoreReplies = (id) => {
    // 标记该评论的回复已展开
    expandedReplies[id] = true;

    // 触发加载更多回复事件
    emit("load-more-replies", { id });
};

// 收起回复
const collapseReplies = (id) => {
    // 取消展开标记
    expandedReplies[id] = false;
};

// 查看全部评论
const viewAllComments = () => {
    emit("view-all");
};

// 文本框获得焦点时的处理
const onTextareaFocus = () => {
    // 确保弹窗完全显示后再聚焦
    setTimeout(() => {
        modalFocused.value = true;
    }, 200);
};

// 文本框失去焦点时的处理
const onTextareaBlur = () => {
    // 延迟重置焦点状态，避免键盘收起时的跳动
    setTimeout(() => {
        modalFocused.value = false;
    }, 300);
};

// 提交评论
const submitComment = () => {
    if (commentContent.value.trim().length === 0) {
        uni.showToast({
            title: "评论内容不能为空",
            icon: "none",
        });
        return;
    }

    const comment = {
        rootId: isReply.value ? comment.rootId : 0,
        parentId: isReply.value ? replyToId.value : null,
        content: commentContent.value,
        // replyId: isReply.value ? replyToReplyId.value : null,
        // replyTo: isReply.value ? replyToUser.value : null
    };

    emit("submit", comment);
    closeCommentModal();
};

// 组件挂载时监听键盘高度变化
onMounted(() => {
    uni.onKeyboardHeightChange(handleKeyboardHeightChange);
});

// 组件卸载时取消监听
onUnmounted(() => {
    uni.offKeyboardHeightChange(handleKeyboardHeightChange);
});
</script>

<style lang="scss" scoped>
.social-comment-container {
    background-color: #fff;
    // padding: 20rpx;
    padding: 10rpx 10rpx;
}

.comment-header {
    padding: 10rpx 0;
    border-bottom: 1rpx solid #f0f0f0;

    .comment-count {
        font-size: 28rpx;
        color: #333;
        font-weight: 500;
    }
}

.comment-input-section {
    padding: 10rpx 0;

    .input-box {
        display: flex;
        align-items: center;
        padding: 20rpx;
        background-color: #f5f5f5;
        border-radius: 30rpx;
        transition: all 0.3s;

        &:active {
            background-color: #e0e0e0;
        }

        .placeholder {
            color: #999;
            font-size: 28rpx;
        }
    }
}

.comment-list {
    margin-top: 10rpx;
}

.comment-item {
    display: flex;
    padding: 10rpx 0;
    border-bottom: 1rpx solid #f5f5f5;

    &:last-child {
        border-bottom: none;
    }

    .user-avatar {
        margin-right: 20rpx;
        flex-shrink: 0;
    }

    .comment-content {
        flex: 1;
        min-width: 0;

        .user-info {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 10rpx;

            .username {
                font-size: 26rpx;
                color: #333;
                font-weight: 500;
                margin-right: 15rpx;
            }

            .time {
                font-size: 22rpx;
                color: #999;
            }
        }

        .comment-text {
            font-size: 28rpx;
            color: #333;
            line-height: 1.5;
            margin-bottom: 15rpx;
            word-wrap: break-word;

            .expand-toggle {
                color: #67b6ff;
                cursor: pointer;
                font-size: 26rpx;
                margin-left: 5rpx;
            }
        }

        .comment-actions {
            display: flex;
            align-items: center;

            .action-item {
                display: flex;
                align-items: center;
                margin-right: 30rpx;
                cursor: pointer;
                padding: 8rpx 10rpx;
                border-radius: 10rpx;
                transition: background-color 0.2s;

                &:active {
                    background-color: #f0f0f0;
                }

                .action-text {
                    font-size: 22rpx;
                    color: #999;
                    margin-left: 8rpx;

                    &.liked {
                        color: #ff0202;
                    }
                }
            }
        }

        .reply-list {
            margin-top: 5rpx;
            background-color: #f8f8f8;
            border-radius: 10rpx;
            padding: 5rpx 10rpx;

            .reply-item {
                display: flex;
                padding: 10rpx 0;
                border-bottom: 1rpx solid #eee;

                &:last-child {
                    border-bottom: none;
                }

                .reply-avatar {
                    margin-right: 15rpx;
                    flex-shrink: 0;
                }

                .reply-content {
                    flex: 1;
                    min-width: 0;

                    .reply-user-info {
                        display: flex;
                        align-items: center;
                        justify-content: space-between;
                        margin-bottom: 8rpx;

                        .reply-username {
                            font-size: 24rpx;
                            color: #333;
                            font-weight: 500;
                            margin-right: 10rpx;
                        }

                        .reply-time {
                            font-size: 20rpx;
                            color: #999;
                        }
                    }

                    .reply-text {
                        font-size: 26rpx;
                        color: #333;
                        line-height: 1.4;
                        margin-bottom: 10rpx;
                        word-wrap: break-word;

                        .expand-toggle {
                            color: #55a1f8;
                            cursor: pointer;
                            font-size: 24rpx;
                            margin-left: 5rpx;
                        }
                    }

                    .reply-actions {
                        display: flex;
                        align-items: center;

                        .action-item {
                            display: flex;
                            align-items: center;
                            margin-right: 20rpx;
                            cursor: pointer;
                            padding: 5rpx 10rpx;
                            border-radius: 8rpx;
                            transition: background-color 0.2s;

                            &:active {
                                background-color: #eee;
                            }

                            .action-text {
                                font-size: 20rpx;
                                color: #999;

                                &.liked {
                                    color: #ff0202;
                                }
                            }
                        }
                    }
                }
            }

            .view-more-replies {
                display: flex;
                align-items: center;
                justify-content: center;
                padding: 15rpx 0;
                cursor: pointer;
                border-radius: 8rpx;
                transition: background-color 0.2s;

                &:active {
                    background-color: #eee;
                }

                .view-more-text {
                    font-size: 24rpx;
                    color: #55a1f8;
                    margin-right: 10rpx;
                }
            }
        }
    }
}

.empty-comments {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 100rpx 0;

    .empty-text {
        font-size: 28rpx;
        color: #999;
        margin-top: 20rpx;
    }
}

.view-all-comments {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 20rpx;
    margin: 20rpx 0;
    background-color: #f5f5f5;
    border-radius: 10rpx;
    cursor: pointer;
    transition: background-color 0.3s;

    &:active {
        background-color: #e0e0e0;
    }

    .view-all-text {
        font-size: 26rpx;
        color: #666;
        margin-right: 10rpx;
    }
}

.comment-modal {
    .modal-header {
        padding: 30rpx;
        text-align: center;
        border-bottom: 1rpx solid #f0f0f0;

        .modal-title {
            font-size: 32rpx;
            color: #333;
            font-weight: 500;
        }
    }

    .reply-info {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 20rpx 30rpx;
        background-color: #f0f8ff;

        .reply-text {
            font-size: 26rpx;
            color: #333;
        }
    }

    .modal-content {
        padding: 20rpx;

        .comment-textarea {
            width: 100%;
            min-height: 200rpx;
            padding: 20rpx;
            border: 1rpx solid #e0e0e0;
            border-radius: 10rpx;
            font-size: 28rpx;
            color: #333;
            box-sizing: border-box;
            resize: none;
            background-color: #fafafa;
            transition: all 0.3s;

            &:focus {
                border-color: #55a1f8;
                background-color: #fff;
                box-shadow: 0 0 0 2rpx rgba(7, 193, 96, 0.2);
            }
        }

        .modal-footer {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-top: 20rpx;
            margin-bottom: 25rpx;

            .char-count {
                font-size: 24rpx;
                color: #999;

                &.char-warning {
                    color: #ff9900;
                }
            }
        }
    }
}
</style>
